﻿using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Himp.Platform
{
    /// <summary>
    /// todo remove
    /// </summary>
    [Route("api/main/mutation/v1")]
    public class ApiMutationController : ApiBaseController
    {
        private IOpenApiService _openApiService;

        public ApiMutationController(IOpenApiService openApiService)
        {
            _openApiService = openApiService;
        }

        [HttpPost]
        public async Task<InternalApiOutput> Post([FromBody] InternalApiInput input)
        {
            InternalApiOutput internalApiOutput = new InternalApiOutput();
            internalApiOutput.RefMsgId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            internalApiOutput.RecvTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            internalApiOutput.ResTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var graphQlClient = new GraphQLHttpClient("https://localhost:44322/graphql/", new NewtonsoftJsonSerializer());
            var mutation = new GraphQLHttpRequest(input.Input);
            var response = await graphQlClient.SendMutationAsync<object>(mutation);

            if (response.Errors?.Any() == true)
            {
                StringBuilder errorSB = new StringBuilder();
                internalApiOutput.InfStasno = -1;
                foreach (var error in response.Errors)
                {
                    errorSB.AppendLine(error.Message);
                }
                internalApiOutput.ErrMsg = errorSB.ToString();
            }
            else
            {
                var dataJson = Newtonsoft.Json.JsonConvert.SerializeObject(response.Data);
                internalApiOutput.Output = dataJson;
            }

            return internalApiOutput;
        }
    }
}
